package cn.bluethink.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * 
 * SpringBoot 读取外部配置文件类
 * 
 * @title 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.1.0
 * @author fanbl 2018年12月3日
 */
public class ZenTaoConfig implements EnvironmentPostProcessor {
	// 动态获取项目配置文件地址（在本机tomcat，webApps下）
	private static final String LOCATION = System.getProperty("catalina.home") + "\\webapps\\"
			+ "application-eguan-zentao.properties";
   
	@Override
	public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment,
			SpringApplication springApplication) {
		File file = new File(LOCATION);
		//判断文件是否存在
		if (file.exists()) {
			MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
			Properties properties = loadProperties(file);
			propertySources.addFirst(new PropertiesPropertySource("Config", properties));
		}
	}
    //加载properties配置文件
	private Properties loadProperties(File f) {
		FileSystemResource resource = new FileSystemResource(f);
		try {
			return PropertiesLoaderUtils.loadProperties(resource);
		} catch (IOException ex) {
			throw new IllegalStateException("Failed to load local settings from " + f.getAbsolutePath(), ex);
		}
	}

}
